<script lang="ts" setup>
// import type { DemoTableApi } from '../mock-api';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal, z } from '@vben/common-ui';

import { ElButton } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
// import { MOCK_API_DATA } from '../table-data';

import { ref } from 'vue';

import { Login_Type } from '@vben/constants';

import dayjs from 'dayjs';
import { VxeGrid } from 'vxe-table';

import {
  addCompanyApi,
  getCompanyListApi,
  userAddApi,
  userDeleteApi,
  userEditApi,
} from '#/api';

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}
const currentUser = ref({});
const sleep = (time = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const comGridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { type: 'expand', width: 80, slots: { content: 'expand_content' } },
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'companyName',
      title: '公司名称',
    },
    {
      field: 'updateTimestamp',
      title: '更新时间',
      slots: { default: 'updateTimestamp' },
    },
    { field: 'remark', title: '备注' },
    {
      field: 'action',
      title: '操作',
      slots: { default: 'action' },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const res = await getCompanyListApi({
          offset: page.currentPage,
          size: page.pageSize,
        });
        return {
          items: res.records,
          total: res.total,
        };
      },
    },
  },
  // data: [
  //   {
  //     id: 1,
  //     comId: 1,
  //     comName: '444',
  //     remark: '111',
  //     children: [
  //       { id: 2, accId: 66, name: '234', remark: 'asdf' },
  //       { id: 2, accId: 66, name: '234', remark: 'asdf' },
  //     ],
  //   },
  //   {
  //     id: 1,
  //     comId: 1,
  //     comName: '444',
  //     remark: '111',
  //     children: [{ id: 2, accId: 66, name: '234', remark: 'asdf' }],
  //   },
  // ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  // keepSource: true,
  // proxyConfig: {
  //   ajax: {
  //     query: ({ page }) => {
  //       return {
  //         total: 0,
  //         items: [{ id: 1, category: '444', children: [{ id: 2 }] }],
  //       };
  //     },
  //   },
  // },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const [ComGrid, comGridApi] = useVbenVxeGrid({
  gridOptions: comGridOptions,
});
// 账号
const gridOptions: VxeGridProps = {
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    //
    { field: 'nickName', title: '姓名' },
    { field: 'email', title: '邮箱' },
    { field: 'phone', title: '手机号' },
    //
    {
      field: 'updateTimestamp',
      title: '更新时间',
      slots: { default: 'updateTimestamp' },
    },
    { field: 'remark', title: '备注' },
    {
      field: 'action',
      title: '操作',
      slots: { default: 'action' },
    },
  ],
  keepSource: true,
};
// const [Grid, GridApi] = useVbenVxeGrid({
//   gridOptions,
// });
const [BaseForm, formApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请填写姓名',
      },
      // 字段名
      fieldName: 'nickName',
      // 界面显示的label
      label: '姓名',
      rules: z.string().min(1, '请填写姓名'),
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'RadioGroup',
      // 对应组件的参数
      componentProps: {
        placeholder: '请选择用户的登录方式',
        options: Login_Type,
      },
      defaultValue: Login_Type[0]?.value,
      // 字段名
      fieldName: 'loginType',
      // 界面显示的label
      label: '登录方式',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入手机号码',
      },
      // 字段名
      fieldName: 'phone',
      // 界面显示的label
      label: '手机号码',
      defaultValue: '',
      dependencies: {
        triggerFields: ['loginType'],
        show(values) {
          const show = values.loginType === 1;
          if (show) {
            values.email = '';
          }
          return show;
        },
      },
      rules: z.string().refine(
        (value) => {
          const res = Number(value);
          if (Number.isNaN(res)) return false;
          return true;
        },
        { message: '请输入正确的手机号码' },
      ),
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入邮箱',
      },
      // 字段名
      fieldName: 'email',
      // 界面显示的label
      label: '邮箱',
      defaultValue: '',
      dependencies: {
        triggerFields: ['loginType'],
        show(values) {
          const show = values.loginType === 2;
          if (show) {
            values.phone = '';
          }
          return show;
        },
      },
      rules: z.string().email('请输入正确的邮箱'),
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入密码',
        showPassword: true,
        type: 'password',
      },
      // 字段名
      fieldName: 'password',
      // 界面显示的label
      label: '密码',
      rules: z.string().min(1, '请填写登录密码'),
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入备注',
        type: 'textarea',
      },
      // 字段名
      fieldName: 'remark',
      // 界面显示的label
      label: '备注',
    },
  ],
});
const companyId = ref('');
const isUserEdit = ref(false);
const [Modal, modalApi] = useVbenModal({
  onConfirm: () => {
    formApi
      .validate()
      .then((res) => {
        return res.valid ? Promise.resolve() : Promise.reject();
      })
      .then(() => {
        return formApi.getValues();
      })
      .then((res) => {
        modalApi.setState({
          loading: true,
        });
        return isUserEdit.value
          ? userEditApi(res)
          : userAddApi({ ...res, companyId: companyId.value });
      })
      .then(
        () => {
          modalApi.setState({
            loading: false,
          });
          modalApi.close();
          return comGridApi.reload();
        },
        () => {
          modalApi.setState({
            loading: false,
          });
        },
      );
  },
});
// 打开用户添加
const openUserModal = (id: string) => {
  isUserEdit.value = false;
  companyId.value = id;
  modalApi.open();
};
// 编辑用户
const editUser = (data: any = {}) => {
  isUserEdit.value = true;
  formApi.setValues(data, false);
  modalApi.open();
};

// 公司

const [ComBaseForm, comformApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请填公司名称',
      },
      // 字段名
      fieldName: 'companyName',
      // 界面显示的label
      label: '公司名称',
      rules: 'required',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请填备注',
      },
      // 字段名
      fieldName: 'remark',
      // 界面显示的label
      label: '备注',
    },
  ],
});
const [ComModal, ComModalApi] = useVbenModal({
  onConfirm: () => {
    comformApi
      .validate()
      .then((res) => {
        return res.valid ? Promise.resolve() : Promise.reject();
      })
      .then(() => {
        return comformApi.getValues();
      })
      .then((res) => {
        return addCompanyApi(res);
      })
      .then(() => {
        return comGridApi.reload();
      })
      .then(() => {
        ComModalApi.close();
      });
  },
});
const [DeleModal, deleModalApi] = useVbenModal({
  onConfirm: () => {
    deleModalApi.setState({
      loading: true,
    });
    userDeleteApi({ id: currentUser.value.id })
      .then(() => {
        deleModalApi.setState({
          loading: false,
        });
        deleModalApi.close();
        comGridApi.reload();
      })
      .catch(() => {
        deleModalApi.setState({
          loading: false,
        });
      });
  },
});
// 删除用户
const deleUser = (data) => {
  currentUser.value = data;
  deleModalApi.open();
};
</script>

<template>
  <div class="vp-raw w-full">
    <ComGrid>
      <template #toolbar-tools>
        <ElButton class="mr-2" type="primary" @click="ComModalApi.open()">
          新增公司
        </ElButton>
      </template>
      <template #updateTimestamp="{ row }">
        {{ dayjs(Number(row.updateTimestamp)).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #action="{ row }">
        <ElButton type="text" @click="openUserModal(row.id)">新增账号</ElButton>
      </template>
      <template #expand_content="{ row }">
        <div class="p-[10px]">
          <VxeGrid :data="row.userInfoList" v-bind="gridOptions">
            <template #action="data">
              <ElButton type="text" @click="editUser(data.row)">编辑</ElButton>
              <ElButton type="text" @click="deleUser(data.row)">
                删除账号
              </ElButton>
            </template>
            <template #updateTimestamp="data">
              {{
                dayjs(Number(data.row.updateTimestamp)).format(
                  'YYYY-MM-DD HH:mm:ss',
                )
              }}
            </template>
          </VxeGrid>
        </div>
      </template>
    </ComGrid>
    <ComModal class="w-[600px]" title="添加公司">
      <ComBaseForm />
    </ComModal>
    <Modal class="w-[600px]" title="添加用户">
      <BaseForm />
    </Modal>
    <DeleModal title="删除用户">
      <div class="flex flex-col gap-[10px]">
        <div>您确定删除该用户？</div>
        <div>用户姓名：{{ currentUser.nickName }}</div>
        <div v-if="currentUser.email">用户邮箱：{{ currentUser.email }}</div>
        <div v-if="currentUser.phone">用户手机号：{{ currentUser.phone }}</div>
        <div>注意：删除后，用户将无法登录。</div>
      </div>
    </DeleModal>
  </div>
</template>
